#pragma once
#include <iostream>
#include <cstdio>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <cstring>
#include <unistd.h>
#include "log.hpp"

using namespace std;


class Udp_serve
{
public:
    Udp_serve(uint16_t port,string ip = "")
    :_port(port)
    ,_ip(ip)
    {}

    void sever_init()//初始化服务器
    {
        //初始化第一步：创建套接字
        _socket = socket(AF_INET,SOCK_DGRAM,0);
        if(_socket < 0)
        {
            logMassage(FATAL,"%d: %s\n",errno,strerror(errno));
            exit(2);
        }
        //初始化第二步，bind
        struct sockaddr_in local;
        memset(&local,0,sizeof local);
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = _ip.empty()?INADDR_ANY: inet_addr(_ip.c_str());

        if(bind(_socket,(struct sockaddr*)&local,sizeof(local))<0)
        {
            logMassage(FATAL,"%d: %s\n",errno,strerror(errno));
            exit(3);
        }
        logMassage(NOEMAL,"init udp sever done %s\n",strerror(errno));
    }
    void start()
    {
        char buffer[1024];
        for(;;)
        {
            struct sockaddr_in peer;
            memset(&peer,0,sizeof peer);
            socklen_t len = sizeof(peer);
            socklen_t sizeofbuffer = recvfrom(_socket,buffer,sizeof(buffer) - 1,0,(struct sockaddr*)&peer,&len);//从网络中接收信息
            if(sizeofbuffer > 0)
            {
                buffer[sizeofbuffer] = '\0';
                uint16_t port = ntohs(peer.sin_port);
                string ip = inet_ntoa(peer.sin_addr);
                printf("[%s] [%d]:%s\n",ip.c_str(),port,buffer);
                sendto(_socket,buffer,strlen(buffer),0,(struct sockaddr*)&peer,len);
            }
            //将收到的数据再发送回去
            
        }
    }
   ~Udp_serve()
    {
        if(_socket > 0) close(_socket);
    }
private:
    string _ip;
    uint16_t _port;
    int _socket;
};